import json
import random,string

from Redis import redis_store
from flask import Blueprint, request, Response, current_app
from model.model import db,Demo1
from config import REDIS_KEY_IMG_CODE,REDIS_KEY_IMG_CODE_TIME,REDIS_KEY_MESSAGE_CODE,REDIS_KEY_MESSAGE_CODE_TIME
from captcha.image import ImageCaptcha
users=Blueprint('/user',__name__)

@users.route('/demo1', methods=['POST'])
def register():
    data=request.json
    code=data.pop('code') #code赋值删除的code值
    mobile=data.pop('mobile')

    print(code)
    print(mobile)

    code1=redis_store.get(REDIS_KEY_IMG_CODE+str(mobile))
    if not code1:
        return {'code':400,'msg':'验证码过期'}

    if code.lower()!=code1.lower().decode():
        return {'code':400,'msg':'验证码不正确'}
    db.session.add(Demo1(**data))
    db.session.commit()
    return {'code':200,'msg':'创建成功'}



#图片验证码联系
@users.route('/demo2', methods=['GET'])
def sessoin():
    params=request.args

    # mobile=params.get('mobile')
    # img_code="".join(random.sample(string.ascii_letters,4))
    # redis_store.setex(REDIS_KEY_IMG_CODE+str(mobile),REDIS_KEY_IMG_CODE_TIME,img_code)
    # number_img=ImageCaptcha()
    # img = number_img.generate(img_code)
    # print('图片验证为'+img_code)
    # return Response(img,mimetype='image/png')
    mobile=params.get('mobile')
    img_code=''.join(random.sample(string.ascii_letters,4))
    redis_store.setex(REDIS_KEY_IMG_CODE+str(mobile),REDIS_KEY_MESSAGE_CODE_TIME,img_code)
    number_img=ImageCaptcha()
    img=number_img.generate(img_code)
    return Response(img,mimetype='image/png')


@users.route('/message', methods=['get'])
def messagecode():
    params=request.args
    mobile=params.get('mobile')
    code=params.get('code')
    from ronglian_sms_sdk import SmsSDK
    sms_sdk = SmsSDK(
        accId=current_app.config['ACC_ID'],
        accToken=current_app.config['ACC_TOKEN'],
        appId=current_app.config['APP_ID']
    )
    sms_code_message=random.randint(100000,999999)
    result=sms_sdk.sendMessage(1,mobile,datas=(sms_code_message,5))
    result_dict = json.loads(result)
    if result_dict['statusCode'] == '000000':
        print(f'短信验证码发送成功：{sms_code_message}')
    else:
        print('短信验证码失败')

    redis=redis_store.setex(REDIS_KEY_MESSAGE_CODE+str(mobile),REDIS_KEY_MESSAGE_CODE_TIME,sms_code_message)
    if not redis:
        return {'code':400,'msg':'短信验证码不存在'}
    return {'code': 200, 'msg': '成功了'}

